<?php
uses('controller');

class usersController extends Controller {

    var $regexp;

    function __construct() {
        parent::__construct();
    }

    function register() {
        $this->debugmsg('usersController::register');

        $data['username']   = trim($this->post['username']);
        $data['password']   = trim($this->post['password']);
        $data['password_r'] = trim($this->post['password_r']);
        $data['email']      = strtolower(trim($this->post['email']));
        $data['camefrom']   = intval($this->post['camefrom']); //推荐人

        $data['nickname'] = $data['username'];

        if ($data['username'] && $data['password'] && $data['email']) {
            /*
            1 成功
            2 已存在
            4 失败
            8 不完整
            16 用户名非法
            32 密码非法
            64 Email非法
            128 确认密码不符
            256 Email已存在
             */
            if (!preg_match($this->regexp['username'], $data['username']))
                $result['code']['register'] += 16;
            elseif (preg_match('/^[0-9]/', $data['username'])) $result['code']['register'] += 16;

            if (!preg_match('/^[\w!@#$%^&_\-\*]{3,16}$/', $data['password'])) $result['code']['register'] += 32;
            if (!$data['email'] || !preg_match($this->regexp['email'], $data['email'])) $result['code']['register'] += 64;
            if ($data['password'] != $data['password_r']) $result['code']['register'] += 128;

            //验证通过
            if (!$result['code']['register']) $result = $this->model->register($data);

        } else {
            if ($this->post && !$data['username']) $result['code']['register'] += 16;
            if ($this->post && !$data['password']) $result['code']['register'] += 32;
            if ($this->post && !$data['email']) $result['code']['register'] += 64;
            if ($this->post) $result['code']['register'] += 8;
        }

        $result['data'] = $data;
        return $result;
    }

    //Login
    function login() {
        $this->debugmsg('usersController::login');

        //登录前网址
        if (isset($this->session['urlfrom']) && !isset($this->request['from'])) $this->request['from'] = $this->session['urlfrom'];

        if ($this->request['logout']) {
            unset($this->session['login'], $this->session['id'], $this->session['username'], $this->session['admin'], $this->session['email'], $this->session['wish']);
            setcookie('username', "", time());
            setcookie('password', "", time());
            setcookie('autologin', "", time());
            setcookie('_cfguest', 0, time());

            do_action('users_logout');

            $this->redirect($this->request['from']);die;
        }

        if (!$this->request['from'] || preg_match('/logout/', $this->request['from'])) $this->request['from'] = '/my/';
        if ($this->session['login'] && $this->session['id']) $this->redirect($this->request['from']);

        $data['sessionid']  = trim($this->session['sid']);
        $data['username']   = trim($this->post['username']);
        if ($this->post['password']) $data['password']   = md5(trim($this->post['password']));
        $data['autologin']  = (int)$this->request['autologin'];


        //AutoLogin
        if (!$this->session['login'] && $this->cookie['autologin'] && $this->cookie['username'] && $this->cookie['password']) {
            if (!$data['username']) $data['username'] = $this->cookie['username'];
            if (!$data['password']) $data['password'] = $this->cookie['password'];
        }

        if ($data['username'] && $data['password']) {
            $result = $this->model->login($data);
        } else {
            /*
            1.用户名为空
            2.密码为空
             */
            if ($this->post && !$data['username']) $result['code']['login'] += 1;
            if ($this->post && !$data['password']) $result['code']['login'] += 2;
        }

        //4.登录成功
        if ($result['code']['login'] == 4) {
            //session
            $this->session['login']     = true;
            $this->session['id']        = $result['rs']['id'];
            $this->session['username']  = $result['rs']['username'];
            $this->session['email']     = $result['rs']['email'];
            $this->session['nickname']  = $result['rs']['nickname'];

            //camefrom - 推荐用户返点
            if ($result['rs']['camefrom'] && !$this->cookie['camefrom']) setcookie('camefrom', $result['rs']['camefrom'], time()+3600*24*7, '/');

            //管理员不允许自动登录
            if ($result['rs']['admin'] == 1) {
                $this->session['admin'] = $result['rs']['admin'];
                //$data['autologin']      = null;
            }

            $this->session['caramount'] = $result['caramount'];
            $this->session['carprice'] = $result['carprice'];

            //autologin
            if ($data['autologin'] == 1) {
                $expire = time() + 3600 * 24 * 30; //One month
                setcookie('username', $data['username'], $expire);
                setcookie('password', $data['password'], $expire);
                setcookie('autologin', 1, $expire);
            }

            //更新购物车
            require_once ROOT.'controllers'.DS.'items.php';
            $ic =& new itemsController;
            $ic->loginIntoShopcar();

            do_action('users_login_succeed', array('result'=>&$result['rs']));

            $this->redirect($this->request['from']);
        } else {
            //自动登录失败则不再重试
            setcookie('username', "", time()-3600);
            setcookie('password', "", time()-3600);
            setcookie('autologin', "", time()-3600);
            do_action('users_login_fail', $this->session['id']);
        }

        $result['data'] = $data;
        return $result;
    }

    //ForgotPWD
    function forgotpwd() {
        $this->debugmsg('usersController::forgotpwd');

        $data['username']   = trim($this->post['username']);
        $data['email']      = trim($this->post['email']);

        if ($data['username'] && $data['email']) {
            if (!preg_match($this->regexp['username'], $data['username'])) $result['code']['forgotpwd'] += 1;
            if (!preg_match($this->regexp['email'], $data['email'])) $result['code']['forgotpwd'] += 2;

            if (!$result['code']['forgotpwd']) $result = $this->model->forgotpwd($data);
        } else {
            /*
            1.用户名为空
            2.email为空
            4.用户名email不匹配
             */
            if ($this->post && !$data['username']) $result['code']['forgotpwd'] += 1;
            if ($this->post && !$data['email']) $result['code']['forgotpwd'] += 2;
        }

        $result['data'] = $data;
        return $result;
    }

    function adminList() {
        $this->debugmsg('usersController::adminList');

        $data['sort'] = ($this->request['sort'] ? strtolower($this->request['sort']) : '');
        $data['sortorder'] = ($this->request['sortorder'] ? strtoupper($this->request['sortorder']) : 'DESC');
        $data['pagesize'] = ($this->request['pagesize'] ? intval($this->request['pagesize']) : $this->pagesize);

        if ($this->request['s']) $data['search'] = trim($this->request['s']);
        if ($this->request['ids']) {
            $this->request['ids'] = explode(',', $this->request['ids']);
            foreach ($this->request['ids'] as $id) $tmp[] = intval($id);
            $data['ids'] = join(',', $tmp);
        }

        $result['data'] = $data;
        $result['list'] = $this->model->usersList($data);

        return $result;
    }

    /*
    1.成功
    2.失败
    4.密码不合法
    8.email不合法
     */
    function adminEdit() {
        $this->debugmsg('usersController::adminEdit');

        $data['id'] = $this->request['id'];
        $data['remove'] = $this->request['remove'];

        if ($data['remove']) $this->needAdmin();

        if ($this->post || $data['remove']) {
            if ($this->post['nickname'])$data['fields']['nickname'] = trim($this->post['nickname']);
            if ($this->post['password'])$data['fields']['password'] = trim($this->post['password']);
            if ($this->post['email'])   $data['fields']['email'] = trim($this->post['email']);
            if ($this->post['truename'])$data['fields']['truename'] = trim($this->post['truename']);

            if ($this->post['rank'])    $data['fields']['rank'] = intval($this->post['rank']);
            if ($this->post['score'])   $data['fields']['score'] = intval($this->post['score']);

            if ($this->post['tel'])     $data['fields']['tel'] = trim($this->post['tel']);
            if ($this->post['address']) $data['fields']['address'] = trim($this->post['address']);
            if ($this->post['zipcode']) $data['fields']['zipcode'] = trim($this->post['zipcode']);

            if ($data['fields']['password'] && !preg_match('/^\w{3,32}$/', $data['fields']['password']))       $result['code']['adminEdit'] += 4;
            if ($data['fields']['email'] && !preg_match($this->regexp['email'], $data['fields']['email']))  $result['code']['adminEdit'] += 8;

            if (!$result['code']['adminEdit']) {
                do_action('users_adminedit_befor', array('data'=>&$data));

                $result = $this->model->usersEdit($data);
                $result['code']['adminEdit'] = $result['code']['usersEdit'];
                $result['ajaxcode'] = 1;
            } else {
                $result['ajaxcode'] = $result['code']['adminEdit'];
            }

            if ($result['remove']) $this->redirect('users.php');
        } else {
            $result['ajaxcode'] = 2;
        }

        $v['ids'] = $data['id'];
        $tmp = $this->model->usersList($v);
        $result['data'] = &$tmp['list'][0];

        return $result;
    }

    function ajaxAdminEdit($var) {
        parse_str($var, $this->post);
        $this->post = array_stripslashes($this->post);

        $result = $this->adminEdit();
        $this->ajax->quickresult($result['ajaxcode']);
    }

    /*
    1.成功
    16.确认密码不符
     */
    function userRegInfo() {
        $this->debugmsg('usersController::userRegInfo');

        $this->needLogin();

        $this->request['id']        = $this->session['id'];
        $this->request['remove']    = false;

        //防止自行更改不可改字段
        unset($this->post['rank'], $this->post['score'], $this->post['camefrom'], $this->post['email']);
        if ($this->post['nickname']) $this->session['nickname'] = $this->post['nickname'];

        //确认密码
        if ($this->post['password'] && ($this->post['password'] != $this->post['password_r'])) {
            $result['code']['userRegInfo'] = 16;
            $result['ajaxcode'] = 16;
        } else {
            $result = $this->adminEdit();
            $result['code']['userRegInfo'] = $result['code']['adminEdit'];
        }

        if (!$result['data']) $result['data'] = $this->request;

        return $result;
    }

    function ajaxuserRegInfo($var) {
        parse_str($var, $this->post);
        $this->request = $this->post = array_stripslashes($this->post);

        $result = $this->userRegInfo();
        $this->ajax->quickresult($result['ajaxcode']);
    }

    //用户中心
    function userCenter() {
        $this->needLogin();
        $result = $this->byId($this->session['id']);

        //销售积分 score
        return $result;
    }

    function userAddress() {
        $this->debugmsg('usersController::userAddress');

        $this->needLogin();

        $data['uid'] = $this->session['id'];

        if($this->request['remove']) //删除
            $result = $this->userAddressDel();
        elseif($this->post['paddr']) //主地址
            $result = $this->userAddressPrimarySet();
        elseif($this->post['aaddr']) //添加
            $result = $this->userAddressAdd();

        $result['list'] = $this->model->userAddressList($data);
        return $result;
    }

    function userWishList() {
        $this->needLogin();

        $data['uid'] = $this->session['id'];
        $data['iid'] = intval($this->request['remove']);

        if($this->request['remove']) $result = $this->model->userWishListDel($data);

        $this->request['id']        = $data['uid'];
        $this->request['remove']    = false;
        $result                     = $this->adminEdit(); // 取得当前wishlist地址

        $data['sort']       = 'updated';
        $data['pagesize']   = 10;
        $result['list']     = $this->model->userWishList($data);

        return $result;
    }

    function ajaxuserWishRemove($var) {
        parse_str($var, $this->post);
        $this->request = $this->post = array_stripslashes($this->post);

        $data['uid'] = $this->session['id'];
        $data['iid'] = intval($this->post['remove']);
        $result = $this->model->userWishListDel($data);

        $this->ajax->quickresult($result['userWishListDel']);
    }

    //wishlist地址
    /*
    4.地址不完整
     */
    function userWishListAddress() {
        $this->needLogin();

        $data['uid'] = $this->session['id'];

        if ($this->post) {
            if (!$this->post['truename'] || !$this->post['tel'] || !$this->post['address'] || !$this->post['zipcode']) {
                $result['code']['userWishListAddress'] = 4;
            } else {
                $data['fields']['truename'] = trim($this->post['truename']);
                $data['fields']['tel']      = trim($this->post['tel']);
                $data['fields']['address']  = trim($this->post['address']);
                $data['fields']['zipcode']  = trim($this->post['zipcode']);
                $result = $this->model->userWishListAddress($data);
            }
        }
        return $result;
    }

    function ajaxuserWishListAddress($var) {
        parse_str($var, $this->post);
        $this->request = $this->post = array_stripslashes($this->post);

        $result = $this->userWishListAddress();
        $this->ajax->quickresult($result['code']['userWishListAddress']);
    }

    //主地址设置
    function userAddressPrimarySet() {
        $this->debugmsg('usersController::userAddressPrimarySet');

        $this->needLogin();

        $data['paddr']  = true;
        $data['id']     = intval($this->post['paddr']);
        $data['uid']    = $this->session['id'];

        $result = $this->model->userAddressUpdate($data);
        $result['ajaxcode'] = $result['code']['userAddressUpdate'] == 1 ? 1 : 2;

        return $result;
    }

    function ajaxuserAddressPrimarySet($var) {
        parse_str($var, $this->post);
        $this->post = array_stripslashes($this->post);

        $result = $this->userAddressPrimarySet();
        $this->ajax->quickresult($result['ajaxcode']);
    }

    function userAddressDel() {
        $this->debugmsg('usersController::userAddressDel');

        $this->needLogin();

        $data['id']     = intval($this->request['remove']);
        $data['remove'] = true;
        $data['uid']    = $this->session['id'];

        return $this->model->userAddressUpdate($data);
    }

    function userAddressAdd() {
        $this->debugmsg('usersController::userAddressDel');

        $this->needLogin();

        $fields['uid']        = $this->session['id'];
        $fields['address']    = trim($this->post['address']);
        $fields['tel']        = trim($this->post['tel']);
        $fields['linkman']    = trim($this->post['linkman']);
        $fields['zipcode']    = intval($this->post['zipcode']);

        if ($fields['address'] && $fields['tel'] && $fields['linkman'] && $fields['zipcode']) return $this->model->userAddressUpdate($fields);

        $data['code']['userAddressUpdate'] = 8;
        $data['data'] = $fields;
        return $data;
    }

    function userUnion() {
        $this->debugmsg('usersController::userUnion');

        $this->needLogin();

        //获取定单明细
        /*
        $ic =& getController('indent');

        $data['camefrom']   = $this->session['id'];
        $data['pagesize']   = 5;
        $data['sortorder']  = 'DESC';
        $data['where']      = "camefrom=".intval($data['camefrom']);

        if ($this->request['all']) {
            $data['pagesize']   = 20;
            $data['all']        = true;
        }

        $result['list']['indent'] = $ic->model->indentsList($data);
        $result['data']['indent'] = $data;
         */

        //获取积分明细
        $sc =& getController('score');

        //查看所有记录
        if ($this->request['show'] == 'score') {
            $data['pagesize'] = 20;
            $data['all'] = true;
        }

        $result['list']['score'] = $sc->userScoreList($data);
        $result['data']['score'] = $data;

        $tmp = $this->byId($this->session['id']);
        $result['score'] = $tmp['score'];

        return $result;
    }

    function byName($name) {
        $this->debugmsg('usersController::byName');
        $data = $this->model->byName($name);

        return $data;
    }

    function byId($id) {
        $this->debugmsg('usersController::byId');
        $data = $this->model->byId($id);

        return $data;
    }

    function byEmail($email) {
        $email = strtolower(trim($email));
        $this->debugmsg('usersController::byEmail');
        $data = $this->model->byEmail($email);

        return $data;
    }

    /* result.code
     * 1.成功
     * 2.OpenID 非法
     * 4.用户取消验证
     * 8.出现异常
     * 16.其它错误
     */
    function openid() {
        uses('openid');

        $openid = trim($this->request['openid_url']);

        //login
        if ($openid && $this->request['openid_action'] == 'login') {

            //登录前网址
            $this->session['urlfrom'] = '/openid.php';
            if (isset($this->request['from'])) $this->session['urlfrom'] = $this->request['from'];

            try {
                $sstr = OpenIDService::performOpenIDLogin($openid);
                if ($sstr == null) {
                    $return['code']['openid'] += 2;
                    return $return;
                }
            }
            catch( Exception $x ){
                $sstr = $x->getMessage();
                $return['code']['openid'] += 8;
                $return['msg'] = $sstr;
                return $return;
            }
        }

        //mode:canceled
        if ($this->request['openid_mode'] == 'cancel') {
            $return['code']['openid'] += 4;
            return $return;
        }

        //mode:id_res
        if ($this->request['janrain_nonce']) {
            $sreg = OpenIDService::confirmOpenIDLogin();

            //认证成功
            if (is_array($sreg)) {
                $return['code']['openid'] = 1;
                $return['msg'] = $sreg['openid'];

                //For suck google
                if ($this->request['openid_ext1_value_email']) $sreg['email'] = $this->request['openid_ext1_value_email'];

                if (!$sreg['nickname']) $sreg['nickname'] = preg_replace('/^([^@]+)@.+/', '$1', $sreg['email']);

                //没有登录用户
                if (!$this->session['id']) {
                    //已经有该用户的记录则直接登录，否则新增
                    if (!$uid = $this->getIdByOpenID($sreg['openid'])) {

                        //email 已经在用户表中存在且唯一，则直接绑定，否则转到自动注册过程
                        $tmp = $this->byEmail($sreg['email']);
                        if (count($tmp) == 1) {
                            $uid = $tmp[0]['id'];
                            $this->addOpenID($sreg['openid'], $uid);
                        } else {
                            $fields['username']     = md5($sreg['openid']);
                            $fields['password']     = md5(rand(1,1000).time());
                            $fields['email']        = $sreg['email'];
                            $fields['truename']     = $sreg['fullname'];
                            $fields['nickname']     = $sreg['nickname'];
                            $fields['created']      = time();


                            if ($sreg['postcode']) $fields['zipcode'] = $sreg['postcode'];

                            $result = $this->model->register($fields);
                            $uid = $result['id'];

                            if ($result['code']['register'] != 1 || !$uid) {
                                //用户注册失败
                                $return['code']['openid'] = 16;
                                $return['msg'] = '用户注册失败';
                                if ($result['code']['register'] & 64) $return['msg'] .= ': 您的 OpenID 中没有正确的 Email 信息, 请修正后再试';
                                if ($result['code']['register'] & 256) $return['msg'] .= ': Email 地址 '.$sreg['email'].' 已经被其它帐号绑定';
                            } else {
                                //新增 OpenID 关系
                                $this->addOpenID($sreg['openid'], $uid);
                            }
                        }
                    }

                    if ($return['code']['openid'] == 1) {
                        if (!$fields) $fields = $this->byId($uid);
                        $this->post['username'] = $fields['username'];
                        $this->post['password'] = $fields['password'];
                        $this->login();
                    }

                } else {
                    //已登录用户只需要再关联一次即可
                    $uid = $this->getIdByOpenID($sreg['openid']);
                    if ($uid && $uid != $this->session['id']) {
                        $return['code']['openid'] = 16;
                        $return['msg'] = '绑定失败: '.$sreg['openid'].' 已经被其它帐号绑定';
                    } else {
                        $this->addOpenID($sreg['openid'], $this->session['id']);
                    }
                }
            } else {
                $return['code']['openid'] += 8;
                $return['msg'] = $sreg;
            }
        }

        if ($this->session['id']) {
            //解除绑定
            if ($this->request['remove'] && $this->request['url']) {
                $return['list']['openid'] = $this->getOpenIDById($this->session['id']);
                //只有一个绑定的时候不允许删除
                if (strlen($this->session['username']) == 32 && count($return['list']['openid']) == 1) {
                    $return['code']['remove'] = 2;
                    return $return;
                } else {
                    $this->delOpenID($this->request['url'], $this->session['id']);
                    $return['code']['remove'] = 1;
                }
            }

            $return['list']['openid'] = $this->getOpenIDById($this->session['id']);
        }

        return $return;
    }

    /**
     * getOpenIDById
     *
     * @param mixed $uid
     * @access public
     * @return void
     */
    function getOpenIDById($uid) {
        $this->debugmsg('usersController::getOpenIDById');
        $data = $this->model->getOpenIDById($uid);
        return $data;
    }

    /**
     * getIdByOpenID
     *
     * @param mixed $url
     * @access public
     * @return void
     */
    function getIdByOpenID($url) {
        $this->debugmsg('usersController::getIdByOpenID');
        $data = $this->model->getIdByOpenID($url);
        return $data;
    }

    /**
     * addOpenID
     *
     * @param mixed $url
     * @param mixed $uid
     * @access public
     * @return void
     */
    function addOpenID($url, $uid) {
        $this->debugmsg('usersController::addOpenID');

        $data['url'] = trim($url);
        $data['uid'] = $uid;

        if ($this->getIdByOpenID($url)) return true;
        $result = $this->model->addOpenID($data);

        return $result ? true : false;
    }

    function delOpenID($url, $uid) {
        $this->debugmsg('usersController::delOpenID');

        $data['url'] = trim($url);
        $data['uid'] = $uid;

        if (!$this->getIdByOpenID($url)) return true;
        $result = $this->model->delOpenID($data);

        return $result ? true : false;
    }

}
?>
